package com.fesine.crm.controller;

import com.fesine.commons.entity.Result;
import com.fesine.commons.enums.ResultEnum;
import com.fesine.commons.util.DateUtils;
import com.fesine.commons.util.ResultUtils;
import com.fesine.crm.exception.CrmException;
import com.fesine.crm.po.LeaveApplyInfoPo;
import com.fesine.crm.service.LeaveApplyInfoService;
import com.fesine.crm.util.SystemUtils;
import com.fesine.dao.model.QueryResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/10/11 21:21
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/10/11 21:21
 */
@RestController
@RequestMapping("/v1")
public class LeaveInfoController {

    @Autowired
    private LeaveApplyInfoService service;

    private static final String dateFormStr = "yyyy-MM-dd";

    /**
     * 获取请假信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取请假信息", httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, dataType = "Integer",
                    paramType = "path")
    })
    @GetMapping("/leave/{id}")
    public Result get(@PathVariable("id") Integer id) {
        LeaveApplyInfoPo po = new LeaveApplyInfoPo();
        po.setId(id);
        po = service.get(po);
        if (po != null) {
            return ResultUtils.success(po);
        }
        throw new CrmException(ResultEnum.NOT_FOUND);
    }

    /**
     * 获取请假信息列表
     *
     * @param request
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation(value = "获取请假信息列表", httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", required = true, dataType = "Integer",
                    paramType = "body"),
            @ApiImplicitParam(name = "limit", required = true, dataType = "Integer", paramType
                    = "body"),
            @ApiImplicitParam(name = "po", dataType =
                    "LeaveApplyInfoPo", paramType = "body")})
    @GetMapping("/leaves")
    public Result list(HttpServletRequest request
            , @RequestParam(required = false) String dateStr
            , @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit) {
        Integer grade = (Integer) request.getSession().getAttribute("grade");
        LeaveApplyInfoPo po = new LeaveApplyInfoPo();
        //普通用户
        if (grade < 1) {
            po.setName((String) request.getSession().getAttribute("name"));
        }
        SystemUtils.setQueryDate(po, dateStr);
        QueryResult<LeaveApplyInfoPo> list = service.listPage(po, page, limit);
        return ResultUtils.success(list);
    }

    @GetMapping("/leaves/query")
    public Result queryList(LeaveApplyInfoPo po
            , @RequestParam(required = false) String dateStr
            , @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit) {
        if (StringUtils.isBlank(po.getName())) {
            po.setName(null);
        }
        SystemUtils.setQueryDate(po, dateStr);
        QueryResult<LeaveApplyInfoPo> list = service.listPage(po, page, limit);
        return ResultUtils.success(list);
    }

    /**
     * 添加请假信息
     * @param po
     * @return
     */
    @ApiOperation(value = "添加请假信息", httpMethod = "POST", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "po", dataType =
                    "LeaveApplyInfoPo", paramType = "body")
    })
    @PostMapping("/leave")
    public Result save(LeaveApplyInfoPo po, @RequestParam String startDateStr,
                       @RequestParam String endDateStr) {

        try {
            Date startTime = DateUtils.formatString(startDateStr, dateFormStr);
            Date endTime = DateUtils.formatString(endDateStr, dateFormStr);
            po.setStartTime(startTime);
            po.setEndTime(endTime);
            int i = service.save(po);
            if (i == 1) {
                return ResultUtils.success(ResultEnum.CREATED, po);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }

    /**
     * 修改请假信息
     * @param po
     * @return
     */
    @ApiOperation(value = "修改请假信息", httpMethod = "PUT", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "po", dataType =
                    "LeaveApplyInfoPo", paramType = "body")
    })
    @PutMapping("/leave/{id}")
    public Result update(@PathVariable("id") Integer id,LeaveApplyInfoPo po, @RequestParam String
            startDateStr,
                         @RequestParam String endDateStr) {

        try {
            Date startTime = DateUtils.formatString(startDateStr, dateFormStr);
            Date endTime = DateUtils.formatString(endDateStr, dateFormStr);
            po.setStartTime(startTime);
            po.setEndTime(endTime);
            int i = service.update(po);
            if (i == 1) {
                return ResultUtils.success(ResultEnum.CREATED, po);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }

    @PutMapping("/leave/status/{status}")
    public Result applyStatus(@PathVariable Integer status,
                              @RequestParam String overIds) {
        String[] idsArr = overIds.split(",");
        LeaveApplyInfoPo po;
        try {
            for (String s : idsArr) {
                po = new LeaveApplyInfoPo();
                po.setId(Integer.parseInt(s));
                po.setStatus(status);
                service.update(po);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new CrmException(ResultEnum.INVALID_REQUEST);
        }
        return ResultUtils.success(ResultEnum.CREATED, overIds);
    }

    /**
     * 删除请假信息
     * @param id
     * @return
     */
    @ApiOperation(value = "删除请假信息", httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = true, dataType = "Integer",
                    paramType = "path")
            })
    @DeleteMapping("/leave/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        LeaveApplyInfoPo po = new LeaveApplyInfoPo();
        po.setId(id);
        int i = service.delete(po);
        if (i == 1) {
            return ResultUtils.success(ResultEnum.DELETED,id);
        }
        throw new CrmException(ResultEnum.INVALID_REQUEST);
    }

    @DeleteMapping("/leaves/{ids}")
    public Result deleteInfos(@PathVariable String ids) {
        String[] idsArr = ids.split(",");
        LeaveApplyInfoPo po;
        try {
            for (String s : idsArr) {
                po = new LeaveApplyInfoPo();
                po.setId(Integer.parseInt(s));
                po = service.get(po);
                service.delete(po);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new CrmException(ResultEnum.INVALID_REQUEST);
        }
        return ResultUtils.success(ResultEnum.DELETED, ids);
    }

}
